package com.imut.lagain.controller;

import com.imut.lagain.entity.User;
import com.imut.lagain.entity.UserRole;
import com.imut.lagain.service.IUserService;
import com.imut.lagain.service.IUserRoleService;
import com.imut.lagain.util.JwtUtil;
import com.imut.lagain.common.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 简单账号密码登录控制器
 */
@RestController
@RequestMapping("/simple-auth")
@RequiredArgsConstructor
public class SimpleAuthController {
    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(SimpleAuthController.class);

    private final IUserService userService;
    private final IUserRoleService userRoleService;
    private final JwtUtil jwtUtil;

    /**
     * 账号密码登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginRequest request) {
        log.info("SimpleAuthController.login called with nickname: {}", request.getNickname());
        try {
            log.info("简单登录请求: nickname={}", request.getNickname());
            
            // 根据昵称查找用户
            User user = userService.findByUsername(request.getNickname());
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 验证管理员密码
            boolean passwordValid = userRoleService.validateAdminPassword(user.getId(), request.getPassword());
            if (!passwordValid) {
                return Result.error("密码错误");
            }
            
            // 生成JWT令牌
            String token = jwtUtil.generateToken(user.getId(), user.getNickname());
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);
            
            log.info("用户登录成功: userId={}, nickname={}", user.getId(), user.getNickname());
            return Result.success(data);
            
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 注册新用户
     */
    @PostMapping("/register")
    public Result<Map<String, Object>> register(@RequestBody RegisterRequest request) {
        log.info("SimpleAuthController.register called with nickname: {}", request.getNickname());
        try {
            log.info("用户注册请求: nickname={}", request.getNickname());
            
            // 检查昵称是否已存在
            User existingUser = userService.findByUsername(request.getNickname());
            if (existingUser != null) {
                return Result.error("昵称已存在");
            }
            
            // 创建新用户
            User newUser = new User();
            newUser.setNickname(request.getNickname());
            newUser.setOpenid("simple_" + System.currentTimeMillis()); // 临时openid
            
            User savedUser = userService.createUser(newUser);
            
            // 创建管理员角色并设置密码
            userRoleService.createUserRole(savedUser.getId(), "ADMIN", "管理员", request.getPassword());
            
            // 生成JWT令牌
            String token = jwtUtil.generateToken(savedUser.getId(), savedUser.getNickname());
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", savedUser);
            
            log.info("用户注册成功: userId={}, nickname={}", savedUser.getId(), savedUser.getNickname());
            return Result.success(data);
            
        } catch (Exception e) {
            log.error("注册失败", e);
            return Result.error("注册失败: " + e.getMessage());
        }
    }
    
    /**
     * 登录请求参数
     */
    public static class LoginRequest {
        private String nickname;
        private String password;
        
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }
    
    /**
     * 注册请求参数
     */
    public static class RegisterRequest {
        private String nickname;
        private String password;
        
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
        public String getPassword() { return password; }
        public void setPassword(String password) { this.password = password; }
    }

    /**
     * 根据用户ID获取用户信息
     */
    @GetMapping("/user/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        log.info("SimpleAuthController.getUserById called with id: {}", id);
        try {
            // 使用MyBatis Plus的selectById方法
            User user = userService.getById(id);
            if (user == null) {
                return Result.error("用户不存在");
            }
            log.info("成功获取用户信息: userId={}, nickname={}", user.getId(), user.getNickname());
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error("获取用户信息失败: " + e.getMessage());
        }
    }
}